package service

import (
	"context"
	"videosS_rpc/basic/config"
	__ "videosS_rpc/basic/proto"
	"videosS_rpc/handler/model"
)

func (s *Server) EpisodeAdd(_ context.Context, in *__.EpisodeAddReq) (*__.EpisodeAddResp, error) {

	episode := model.Episode{
		EpisodeId:  int(in.EpisodeId),
		Title:      in.Title,
		Duration:   in.Duration,
		UpdateTime: in.UpdateTime,
		VIPLogs:    int(in.VIPLogs),
		VideoId:    int(in.VideoId),
		PlayTime:   in.PlayTime,
	}
	err := episode.EpisodeAdd(config.DB)
	if err != nil {
		return nil, err
	}

	return &__.EpisodeAddResp{
		Episode: int64(episode.ID),
	}, nil
}

func (s *Server) IsEpisodeUser(_ context.Context, in *__.IsEpisodeUserReq) (*__.IsEpisodeUserResp, error) {

	episode := model.Episode{}
	err := episode.IsEpisodeUser(config.DB, int(in.VIPLogs), int(in.UserId))
	if err != nil {
		return nil, err
	}
	return &__.IsEpisodeUserResp{
		EpisodeId:  int64(episode.EpisodeId),
		Title:      episode.Title,
		Duration:   episode.Duration,
		UpdateTime: episode.UpdateTime,
		VIPLogs:    int64(episode.VIPLogs),
		VideoId:    int64(episode.VideoId),
		PlayTime:   episode.PlayTime,
		UserId:     int64(episode.UserId),
	}, nil
}

func (s *Server) EpisodeList(_ context.Context, in *__.EpisodeListReq) (*__.EpisodeListResp, error) {

	episode := model.Episode{}
	list, err := episode.EpisodeList(config.DB, int(in.Size), int(in.Page))
	if err != nil {
		return nil, err
	}

	return &__.EpisodeListResp{
		EpList: list,
	}, nil
}
func (s *Server) ISEpisodeList(_ context.Context, in *__.ISEpisodeListReq) (*__.ISEpisodeListResp, error) {

	episode := model.Episode{}
	list, err := episode.EpisodeList(config.DB, int(in.Size), int(in.Page))
	if err != nil {
		return nil, err
	}
	//var EpisodeList []*__.EpisodeLis
	//var size int
	//var page int
	//var wg sync.WaitGroup
	//for _, lists := range EpisodeList {
	//	wg.Add(1)
	//	go func(i int, title string) {
	//		defer wg.Done()
	//
	//		// Build the request body.
	//		data, err := json.Marshal(lists.UserId)
	//		if err != nil {
	//			log.Fatalf("Error marshaling document: %s", err)
	//		}
	//
	//		// Set up the request object.
	//		req := esapi.IndexRequest{
	//			Index:      "aa_video",
	//			DocumentID: strconv.Itoa(int(episode.ID)),
	//			Body:       bytes.NewReader(data),
	//			Refresh:    "true",
	//		}
	//		// Perform the request with the client.
	//		res, err := req.Do(context.Background(), config.EsIni)
	//		if err != nil {
	//			log.Fatalf("Error getting response: %s", err)
	//		}
	//		defer res.Body.Close()
	//
	//
	//
	//	}()
	//}
	//wg.Wait()

	return &__.ISEpisodeListResp{
		EpList: list,
	}, nil
}

func (s *Server) EpisodeDEl(_ context.Context, in *__.EpisodeDElReq) (*__.EpisodeDElResp, error) {

	episode := model.Episode{}
	err := episode.EpisodeDEl(config.DB, int(in.Id))
	if err != nil {
		return nil, err
	}

	return &__.EpisodeDElResp{}, nil
}
